#include "freertosAPP.h"

#include "../bsp/bsp.h"
#include "../model/model.h"
static void taskinit();

static void ledBlinkTask();
static void readDh11Task();
static void sendDataTask();
void freeRtosInit()
{
    taskinit();
    vTaskDelete(NULL); // 如果主任务没有其他工作，可以删除自身
}

void taskinit()
{
    xTaskCreate(ledBlinkTask, "LED Blink Task", configMINIMAL_STACK_SIZE, (void*)LED_pin, 5, NULL);
	xTaskCreate(readDh11Task, "DH11 Read Task", configMINIMAL_STACK_SIZE*2, (void*)LED_pin, 2, NULL);
	xTaskCreate(sendDataTask, "sendDataTask", configMINIMAL_STACK_SIZE*2, (void*)LED_pin, 3, NULL);
}

void ledBlinkTask(){
	const int LEDC_TEST_DUTY = 0x1FFF/2;
	const int LEDC_TEST_FADE_TIME = 1000;
	    // 安装渐变功能
    ledc_fade_func_install(0);
    while(1)
    {
		ledc_set_fade_with_time(
			ledc_channel.speed_mode,
			ledc_channel.channel, 
			LEDC_TEST_DUTY,
			LEDC_TEST_FADE_TIME);
		ledc_fade_start(
			ledc_channel.speed_mode,
			ledc_channel.channel, 
			LEDC_FADE_NO_WAIT);
	vTaskDelay(LEDC_TEST_FADE_TIME / portTICK_PERIOD_MS+100);
	
		ledc_set_fade_with_time(
			ledc_channel.speed_mode,
			ledc_channel.channel, 
			LEDC_TEST_DUTY/20, 
			LEDC_TEST_FADE_TIME);
		ledc_fade_start(
			ledc_channel.speed_mode,
			ledc_channel.channel, 
			LEDC_FADE_NO_WAIT);
	vTaskDelay(LEDC_TEST_FADE_TIME*1.5 / portTICK_PERIOD_MS);
    }
}
static	uchar Humi, Humi_small,Temp, Temp_small;
void readDh11Task()
{


	while (1)
	{
		// OutputLow();
		// vTaskDelay(19 / portTICK_PERIOD_MS);
		DH11Read(&Humi,&Humi_small,&Temp,&Temp_small);
		//printf("Temp=%d.%d℃--Humi=%d.%d RH \r\n",Temp,Temp_small,Humi,Humi_small);
		vTaskDelay(200);

	}
	
}

void sendDataTask()
{
		char buffer[16];
	while (1)
	{
		// OutputLow();
		// vTaskDelay(19 / portTICK_PERIOD_MS);
    	//sprintf(buffer, "%d.%d;%d.%d", Temp,Temp_small,Humi,Humi_small); // "%d" 是整数的格式化指定符
		//int msg_id = 
		esp_mqtt_client_publish(client, "/topic/qos0", buffer, 0, 0, 0);
		vTaskDelay(5000 / portTICK_PERIOD_MS);

	}
}
